package com.xiaotu.filter;

import com.alibaba.fastjson.JSONObject;
import com.xiaotu.constant.CommonConstants;
import com.xiaotu.model.PlayerModel;
import com.xiaotu.service.redission.impl.RedissionServiceImpl;
import com.xiaotu.util.R;
import com.xiaotu.util.SpringUtil;
import com.xiaotu.util.TokenUtil;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户token验证
 *
 * @author zhangxiao
 * @create 2021-01-11 19:59
 */

public class UserTokenFilter extends OncePerRequestFilter {

    private String[] exclusionFilter = {"/battleSocket", "/login", "/register", "/userAgreement", "/verifyCodeManager", "/uploadFile", "/upload", "/favicon.ico",
            "/playerEquipment/buyPropsCard", "/levelRule/endOfGame", "/playerEquipment/consumePropsCard", "/monitorSocket"};

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI();
        logger.debug("request uri:" + request.getRequestURI());
        logger.debug("request refer:" + request.getHeader("Referer"));
        logger.debug("request user-agent:" + request.getHeader("user-agent"));
        logger.debug("request authorization:" + request.getHeader("authorization"));
        logger.debug("request remoteHost:" + request.getRemoteHost());
        boolean isFilter = false;
        for (String e : exclusionFilter) {
            if (uri.indexOf(e) != -1) {
                isFilter = true;
            }
        }
        if (!isFilter) {
            boolean verifyToken = false;
            if (null != request.getHeader("authorization")) {
                logger.debug("验证是否携带：authorization");
                verifyToken = TokenUtil.verifyToken(TokenUtil.getAuthorization(request));
            }
            if (verifyToken) {
                PlayerModel userInfo = TokenUtil.getGloGlobalCache(request, "userInfo", PlayerModel.class);
                if (SpringUtil.getBean("redissionServiceImpl", RedissionServiceImpl.class).validPhoneToken(userInfo.getPhone(), TokenUtil.getAuthorization(request))) {
                    logger.debug("验证authorization: success");
                    request.setAttribute("phone", userInfo.getPhone());
                    request.setAttribute("playerId", userInfo.getPlayerId());
                    filterChain.doFilter(request, response);
                } else {
                    logger.debug("验证authorization: fail");
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json; charset=utf-8");
                    response.getWriter().append(JSONObject.toJSON(R.failed(CommonConstants.SQUEEZE_OUT, "token verify fail !", new Object())).toString());
                }
            } else {
                logger.debug("验证authorization: fail");
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().append(JSONObject.toJSON(R.failed(CommonConstants.TOKEN_EXPIRED, "token verify fail or expired !", new Object())).toString());
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }
}


